

import 'dart:math';
import 'package:ble2025_plugin/ble2203_plugin.dart';
import 'package:ble2025_plugin_example/util/app_all_value.dart';
import 'package:ble2025_plugin_example/util/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

///久坐提醒
class SedentaryReminderPage extends StatefulWidget {
  const SedentaryReminderPage({Key? key}) : super(key: key);

  @override
  State<SedentaryReminderPage> createState() => _SedentaryReminderPageState();
}

class _SedentaryReminderPageState extends State<SedentaryReminderPage> {

  int startHour = 0;
  int startMinute = 0;
  int endHour = 0;
  int endMinute = 0;
  List<bool> weeks = [false,false,false,false,false,false,false];
  var intervalController = TextEditingController();
  var stepController = TextEditingController();

  AppAllValueController controller = Get.find();

  @override
  void initState() {
    super.initState();
    EventBus().on('dataCallBack', (arg) {
      Map maps = arg;
      switch(maps[DeviceKey.DataType] as String){
        case BleConst.SetSedentaryReminder:
          controller.showContentDialog(maps.toString());
          break;
        case BleConst.GetSedentaryReminder:
          Map data = maps[DeviceKey.Data];
          String timeInterval = data[DeviceKey.IntervalTime];
          String week = data[DeviceKey.Week];
          String step = int.parse(data[DeviceKey.LeastSteps]).toString();
          List<String> weekStrings = week.split("-");
          setState(() {
            startHour = int.parse(data[DeviceKey.StartTimeHour]);
            startMinute = int.parse(data[DeviceKey.StartTimeMin]);
            endHour = int.parse(data[DeviceKey.EndTimeHour]);
            endMinute = int.parse(data[DeviceKey.EndTimeMin]);
            for(int i = 0;i < weekStrings.length; i++){
              weeks[i] = weekStrings[i] == '1';
            }
            intervalController.text = timeInterval;
            stepController.text = step;
          });
          break;
      }

    });
  }

  @override
  void dispose() {
    super.dispose();
    EventBus().off('dataCallBack');
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("久坐提醒".tr),
      ),
      body: Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          Row(
            children: [
              Expanded(child: Container(
                margin: const EdgeInsets.only(left: 10,right: 10),
                child: ElevatedButton(
                  child: Text('开始时间'.tr),
                  onPressed: (){
                    showTimePicker(context: context, initialTime: TimeOfDay.now()).then((value){
                      if(value != null){
                        setState(() {
                          startHour = value.hour;
                          startMinute = value.minute;
                        });
                      }
                    });
                  },
                ),
              )),
              Expanded(child: Container(
                margin: const EdgeInsets.only(right: 10),
                child: ElevatedButton(
                  child: Text('结束时间'.tr),
                  onPressed: (){
                    showTimePicker(context: context, initialTime: TimeOfDay.now()).then((value){
                      if(value != null){
                        setState(() {
                          endHour = value.hour;
                          endMinute = value.minute;
                        });
                      }
                    });
                  },
                ),
              ))
            ],
          ),
          Row(
            children: [
              Expanded(child: Container(
                margin: const EdgeInsets.only(left: 10,right: 10),
                child: ElevatedButton(
                  onPressed: null,
                  child: Text('$startHour:$startMinute'),
                ),
              )),
              Expanded(child: Container(
                margin: const EdgeInsets.only(right: 10),
                child: ElevatedButton(
                  onPressed:null,
                  child: Text('$endHour:$endMinute'),
                ),
              ))
            ],
          ),
          Container(
            margin: const EdgeInsets.only(top: 10,bottom: 5),
            alignment: Alignment.center,
            child: Text('星期选择'.tr),
          ),
          GridView(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3,childAspectRatio: 4/1),
            shrinkWrap: true,
            children: [
              buildWeekWidget(0,"周日".tr),
              buildWeekWidget(1,"周一".tr),
              buildWeekWidget(2,"周二".tr),
              buildWeekWidget(3,"周三".tr),
              buildWeekWidget(4,"周四".tr),
              buildWeekWidget(5,"周五".tr),
              buildWeekWidget(6,"周六".tr),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            children: [
              Text('  ${'最小间隔'.tr} '),
              Container(
                width: 100,
                child: TextField(
                  controller: intervalController,
                  textAlign: TextAlign.center,
                  keyboardType: TextInputType.number,
                  textInputAction: TextInputAction.next,
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp('[0-9]')),//只允许输入数
                  ],
                ),
              ),
              Text('分钟'.tr),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            children: [
              Text('  ${'最小间隔'.tr} '),
              Container(
                width: 100,
                child: TextField(
                  controller: stepController,
                  textAlign: TextAlign.center,
                  keyboardType: TextInputType.number,
                  textInputAction: TextInputAction.next,
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp('[0-9]')),//只允许输入数
                  ],
                ),
              ),
              Text('步'.tr),
            ],
          ),
          Row(
            children: [
              Expanded(child: Container(
                margin: const EdgeInsets.only(left: 10,right: 10),
                child: ElevatedButton(
                  child: Text('获取'.tr),
                  onPressed: (){
                    controller.writeData(BleSDK.GetSedentaryReminder());
                  },
                ),
              )),
              Expanded(child: Container(
                margin: const EdgeInsets.only(right: 10),
                child: ElevatedButton(
                  child: Text('设置'.tr),
                  onPressed: (){
                    if(intervalController.text.isEmpty)return;
                    if(stepController.text.isEmpty)return;
                    int week = 0;
                    for(int i = 0; i < weeks.length;i++){
                      if(weeks[i]){
                        week += pow(2, i).toInt();
                      }
                    }
                    var sportPeriod = MySedentaryReminder(
                        startHour: startHour,
                        startMinute: startMinute,
                        endHour: endHour, endMinute: endMinute,
                      week: week,
                      intervalTime: int.parse(intervalController.text),
                      leastStep: int.parse(stepController.text),
                      enable: true,
                    );
                    controller.writeData(BleSDK.SetSedentaryReminder(sportPeriod));
                  },
                ),
              ))
            ],
          ),
        ],
      ),
    );
  }

  Widget buildWeekWidget(int index,String text){
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Checkbox(
          value: weeks[index],
          activeColor: Colors.blue, //选中时的颜色
          onChanged:(value){
            if(value != null){
              setState(() {
                weeks[index]=value;
              });
            }
          } ,
        ),
        Text(text)
      ],
    );
  }
}
